package com.crazymaker.springcloud.websocket.service.impl;

import com.crazymaker.push.platform.contract.constants.PushConstants;
import com.crazymaker.springcloud.common.util.JsonUtil;
import com.crazymaker.springcloud.message.dao.MsgDao;
import com.crazymaker.springcloud.message.dao.MsgStreamDao;
import com.crazymaker.springcloud.message.dao.po.MsgPO;
import com.crazymaker.springcloud.websocket.session.SessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service
public class WebserviceMsgProcessImpl {

    @Resource
    private MsgDao msgDao;

    @Resource
    private MsgStreamDao msgStreamDao;


    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void updateAndSend(String json) {

        MsgPO po = JsonUtil.jsonToPojo(json, MsgPO.class);

        //发送的时候，设置的规则
//        po.setExtField1(messagePO.getAppId().toString());
//        po.setExtField2(streamPO.getTargetId());
//        po.setExtField3(streamPO.getStreamId().toString());

        String appId = po.getExtField1();
        String account = po.getExtField2();
        Long streamId = Long.valueOf(po.getExtField3());
        boolean isOnline = SessionManager.getSingleton().isOnline(appId, account);


        if (isOnline) {

            msgStreamDao.updateStatusByStreamId(PushConstants.PUSHED_BUT_UN_READ,streamId);

            SessionManager.getSingleton().syncSendMsg(appId, account, json);


        } else {

            //用户登陆的时候，查询历史信息，统一推送给他
        }

    }


}
